<template>
  <div>
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="leading-30px">
          <div class="inline-block">
            <svg-icon
              :icon-class="'svg_xmcj'"
              class="w-30px h-30px align-middle"
            />
            <span
              class="text-#000 leading-30px ml-10px text-16px font-bold align-bottom"
              >项目创建审批</span
            >
          </div>
          <div
            v-if="bpmnStatus"
            class="inline-block text-15px ml-10px"
            style="vertical-align: bottom"
          >
            <i
              :class="
                bpmnStatus == '审批通过'
                  ? 'h-8px w-8px bg-#fe9400 inline-block rounded'
                  : bpmnStatus == '流程未发起'
                  ? 'h-8px w-8px bg-#ccc inline-block rounded'
                  : 'h-8px w-8px bg-#10d070 inline-block rounded'
              "
            ></i>
            {{ bpmnStatus }}
          </div>
        </div>
        <!-- 内容 -->
        <div class="text-right">
          <slot></slot>
          <el-button
            v-if="
              (formParam.proSchedule == 3 &&
                projectClosing_isCanStart &&
                formParam.proType == '1' &&
                formParam.biddingResult == 1) ||
              (formParam.proSchedule == 3 &&
                projectClosing_isCanStart &&
                formParam.proType == '2')
            "
            plain
            type="primary"
            @click="projectClose()"
            >发起项目完结申请
          </el-button>
          <el-button
            v-if="formParam.proSchedule == 1 && isCanStart && isExamine"
            plain
            type="primary"
            @click="handleSaveFn('examine', 'initiate')"
            >发起申请
          </el-button>
          <el-button
            v-if="isEdit"
            plain
            type="primary"
            @click="isFlow ? handleSaveFn() : stagingFn()"
            >保存
          </el-button>
          <el-button plain type="primary" @click="handleBack">返回</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="py-20px projectM_sty">
      <el-form
        ref="ruleFormRef"
        :disabled="!isEdit"
        :model="formParam"
        :rules="formRules"
        label-position="right"
        label-width="190"
      >
        <el-collapse v-model="activeNames">
          <!-- 基本信息 -->
          <el-collapse-item disabled name="1">
            <template #title>
              <TitleName
                class="title text-#000 ml-20px"
                icon="i-carbon-bookmark-filled"
                title="基本信息"
              ></TitleName>
            </template>
            <el-row :gutter="grid" class="px-20">
              <el-col :span="gridCol">
                <el-form-item label="项目名称：" prop="proName">
                  <el-input
                    v-model="formParam.proName"
                    clearable
                    maxlength="50"
                    placeholder="请输入项目名称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目属性：" prop="proType">
                  <el-radio-group
                    v-model="formParam.proType"
                    :disabled="isProType"
                  >
                    <el-radio
                      v-for="(dict, index) in project_properties"
                      :key="index"
                      :label="dict.value"
                      border
                      >{{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目编号：" prop="proNum">
                  <el-input
                    v-model="formParam.proNum"
                    clearable
                    maxlength="30"
                    placeholder="请输入招标编号，如无招标编号系统将自动生成"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="客户名称：" prop="customer">
                  <el-input
                    v-model="formParam.customer"
                    :suffix-icon="'el-icon-search'"
                    clearable
                    placeholder="请选择客户名称"
                    @clear="clearAll('customer')"
                    @click="activeDialog('customer')"
                  ></el-input>
                  <!-- <el-select
                                                                                                                                                                                                                          v-model="formParam.cusId"
                                                                                                                                                                                                                          placeholder="请输入客户名称"
                                                                                                                                                                                                                          class="w-full"
                                                                                                                                                                                                                          filterable
                                                                                                                                                                                                                          remote
                                                                                                                                                                                                                          suffix-icon="Search"
                                                                                                                                                                                                                          remote-show-suffix
                                                                                                                                                                                                                          :suffix-transition="false"
                                                                                                                                                                                                                          clearable
                                                                                                                                                                                                                          :loading="loadingSelect"
                                                                                                                                                                                                                          :loading-text="'加载中...'"
                                                                                                                                                                                                                          @change="changeCustomer"
                                                                                                                                                                                                                          :remote-method="queryCustomer"
                                                                                                                                                                                                                        >
                                                                                                                                                                                                                          <el-option
                                                                                                                                                                                                                            v-for="item in parentOptions"
                                                                                                                                                                                                                            :key="item.id"
                                                                                                                                                                                                                            :label="item.customerName"
                                                                                                                                                                                                                            :value="item.id"
                                                                                                                                                                                                                          >
                                                                                                                                                                                                                            <div>
                                                                                                                                                                                                                              <span>{{ item.customerName }}</span>
                                                                                                                                                                                                                              <span v-if="item.mainContactName"
                                                                                                                                                                                                                                >({{ item.mainContactName }})</span
                                                                                                                                                                                                                              >
                                                                                                                                                                                                                              <span v-else>{{ item.mainContactName }}</span>
                                                                                                                                                                                                                            </div>
                                                                                                                                                                                                                          </el-option>
                                                                                                                                                                                                                        </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目阶段：" prop="proSchedule">
                  <el-select
                    v-model="formParam.proSchedule"
                    class="w-full"
                    clearable
                    disabled
                    placeholder="请选择项目阶段"
                  >
                    <el-option
                      v-for="(dict, index) in project_phase"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="业务属性：" prop="busType">
                  <el-select
                    v-model="formParam.busType"
                    class="w-full"
                    clearable
                    placeholder="请选择业务属性"
                  >
                    <el-option
                      v-for="(dict, index) in business_attribute"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="归属单位：" prop="companyId">
                  <el-tree-select
                    ref="companyIdRef"
                    v-model="formParam.companyId"
                    :data="companyOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                    clearable
                    filterable
                    placeholder="请选择归属单位"
                    style="width: 100%"
                    value-key="id"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item
                  v-if="formParam.cusType == 'customer'"
                  label="客户联系人："
                  prop="cusLinkId"
                >
                  <el-select
                    v-model="formParam.cusLinkId"
                    :loading="cuslinkLoading"
                    :loading-text="'加载中...'"
                    :remote-method="queryContacts"
                    :suffix-transition="false"
                    allow-create
                    class="w-full"
                    default-first-option
                    filterable
                    placeholder="请选择客户联系人"
                    remote
                    remote-show-suffix
                    suffix-icon="Search"
                    @change="contactsChange"
                  >
                    <el-option
                      v-for="item in contactsOptions"
                      :key="item.id"
                      :label="item.contactName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.contactName }}</span>
                        <span v-if="item.contactNumber"
                          >({{ item.contactNumber }})</span
                        >
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-else label="客户联系人：" prop="cusLinkName">
                  <el-input
                    v-model="formParam.cusLinkName"
                    :disabled="formParam.cusType == 'cusLink' ? true : false"
                    placeholder="请选择客户联系人"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目负责人：" prop="principalId">
                  <el-select
                    v-model="formParam.principalId"
                    class="w-full"
                    clearable
                    placeholder="请选择项目负责人"
                    @focus="userInputFocus"
                  >
                    <el-option
                      v-for="(item, index) in selectOptionObj['principalId']"
                      :key="index"
                      :label="item.label"
                      :value="item.uuid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="联系电话：" prop="phone">
                  <el-input
                    v-model="formParam.phone"
                    clearable
                    placeholder="请输入联系电话"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目金额：" prop="proSum">
                  <el-input
                    v-model="formParam.proSum"
                    maxlength="20"
                    placeholder="请输入项目金额"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="关联项目：" prop="linkProjectName">
                  <el-input
                    v-model="formParam.linkProjectName"
                    :suffix-icon="'el-icon-search'"
                    clearable
                    placeholder="请选择关联项目"
                    @clear="clearAll('linkProject')"
                    @click="activeDialog('linkProject')"
                  ></el-input>
                  <!-- <el-select
                                                                                                                                                                                                                          v-model="formParam.linkProjectId"
                                                                                                                                                                                                                          placeholder="请输入关联项目名称"
                                                                                                                                                                                                                          class="w-full"
                                                                                                                                                                                                                          filterable
                                                                                                                                                                                                                          remote
                                                                                                                                                                                                                          suffix-icon="Search"
                                                                                                                                                                                                                          remote-show-suffix
                                                                                                                                                                                                                          :suffix-transition="false"
                                                                                                                                                                                                                          clearable
                                                                                                                                                                                                                          :remote-method="queryProject"
                                                                                                                                                                                                                          :loading="loadingSelect"
                                                                                                                                                                                                                          no-data-text="未查询到项目"
                                                                                                                                                                                                                        >
                                                                                                                                                                                                                          <el-option
                                                                                                                                                                                                                            v-for="item in projectOptions"
                                                                                                                                                                                                                            :key="item.projectId"
                                                                                                                                                                                                                            :label="item.proName"
                                                                                                                                                                                                                            :value="item.projectId"
                                                                                                                                                                                                                          >
                                                                                                                                                                                                                            <div>
                                                                                                                                                                                                                              <span>{{ item.proName }}</span>
                                                                                                                                                                                                                            </div>
                                                                                                                                                                                                                          </el-option>
                                                                                                                                                                                                                        </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="投标单位：" prop="tenderer">
                  <el-select
                    v-model="formParam.tenderer"
                    class="w-full"
                    clearable
                    placeholder="请选择投标单位"
                  >
                    <el-option
                      v-for="(dict, index) in bidding_unit"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="业务归属：" prop="businessBelong">
                  <el-select
                    v-model="formParam.businessBelong"
                    class="w-full"
                    clearable
                    placeholder="请选择业务归属"
                  >
                    <el-option value="ZW" label="政务"></el-option>
                    <el-option value="QY" label="企业"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目描述：" prop="proRemark">
                  <el-input
                    v-model="formParam.proRemark"
                    :rows="6"
                    clearable
                    maxlength="500"
                    placeholder="请输入项目描述"
                    show-word-limit
                    type="textarea"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目所需材料：" prop="materials">
                  <el-input
                    v-model="formParam.materials"
                    :rows="6"
                    clearable
                    maxlength="500"
                    placeholder="请输入项目所需材料"
                    show-word-limit
                    type="textarea"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="附件：">
                  <el-upload
                    v-model:file-list="formParam.fileList_ht"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleFileChange"
                    :show-file-list="false"
                    accept=".rar, .zip, .doc, .docx, .pdf"
                    action="#"
                    class="upload-demo"
                  >
                    <el-button
                      style="font-size: 14px"
                      type="default"
                      @click="() => (fileBtnType = 2)"
                    >
                      <el-icon>
                        <UploadFilled />
                      </el-icon>
                      上传文件
                    </el-button>
                    <template #tip>
                      <div class="el-upload__tip float-right">
                        支持格式：.rar .zip .doc .docx .pdf
                        ，单个文件不能超过20MB
                      </div>
                    </template>
                  </el-upload>
                  <div class="text-14px mt-10px" style="width: 100%">
                    <div
                      v-for="(item, index) in fileList_ht"
                      :key="item.fileId"
                    >
                      <a
                        :href="item.url"
                        class="text-#409eff"
                        target="_blank"
                        >{{ item.origFileName }}</a
                      >
                      <el-button plain text @click="delFileName(index, '2')"
                        >删除
                      </el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 招标信息 -->
          <el-collapse-item v-if="formParam.proType == 1" disabled name="2">
            <template #title>
              <TitleName
                class="title text-#000000 ml-20px"
                icon="i-carbon-bookmark-filled"
                title="招标信息"
              ></TitleName>
            </template>
            <el-row :gutter="grid" class="px-20">
              <el-col :span="gridCol">
                <el-form-item label="招标形式：" prop="tenderType">
                  <el-select
                    v-model="formParam.tenderType"
                    class="w-full"
                    clearable
                    placeholder="请选择招标形式"
                  >
                    <el-option
                      v-for="(dict, index) in bidding_form"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目规模：" prop="projectScale">
                  <el-input
                    v-model="formParam.projectScale"
                    clearable
                    maxlength="20"
                    placeholder="请输入标的金额"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="开标时间：" prop="bidOpeningTime">
                  <el-date-picker
                    v-model="formParam.bidOpeningTime"
                    clearable
                    placeholder="请选择开标时间"
                    style="width: 100%"
                    type="date"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="开标提醒：" prop="bidOpeningReminder">
                  <el-select
                    v-model="formParam.bidOpeningReminder"
                    class="w-full"
                    clearable
                    placeholder="请选择开标提醒"
                  >
                    <el-option
                      v-for="(dict, index) in reminder_opening"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="提醒方式：" prop="reminderType">
                  <el-checkbox-group v-model="formParam.reminderType">
                    <el-checkbox
                      v-for="(dict, index) in reminder_method"
                      :key="index"
                      :label="dict.value"
                    >
                      {{ dict.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="fileIcon_style" label="招标文件：">
                  <el-upload
                    v-model:file-list="formParam.fileList_zb"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleFileChange"
                    :show-file-list="false"
                    accept=".rar, .zip, .doc, .docx, .pdf"
                    action="#"
                    class="upload-demo"
                  >
                    <el-button
                      style="font-size: 14px"
                      type="default"
                      @click="() => (fileBtnType = 1)"
                    >
                      <el-icon>
                        <UploadFilled />
                      </el-icon>
                      上传招标文件
                    </el-button>
                    <template #tip>
                      <div class="el-upload__tip float-right">
                        支持格式：.rar .zip .doc .docx .pdf
                        ，单个文件不能超过20MB
                      </div>
                    </template>
                  </el-upload>
                  <div class="text-14px mt-10px" style="width: 100%">
                    <div
                      v-for="(item, index) in fileList_zb"
                      :key="item.fileId"
                    >
                      <a
                        :href="item.url"
                        class="text-#409eff"
                        target="_blank"
                        >{{ item.origFileName }}</a
                      >
                      <el-button plain text @click="delFileName(index, 1)"
                        >删除
                      </el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 投标项目财务情况 -->
          <el-collapse-item v-if="formParam.proType == 1" disabled name="3">
            <template #title>
              <title-name
                class="title text-#000000 ml-20px"
                icon="i-carbon-bookmark-filled"
                title="投标项目财务情况"
              />
            </template>
            <el-row :gutter="grid" class="px-20">
              <el-col :span="gridCol">
                <el-form-item label="项目资金来源：" prop="proSumResouce">
                  <el-input
                    v-model="formParam.proSumResouce"
                    clearable
                    maxlength="20"
                    placeholder="请输入项目资金来源"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="gridCol">
                <el-form-item label="项目付款期限：" prop="proPaymentDeadline">
                  <el-input
                    v-model="formParam.proPaymentDeadline"
                    clearable
                    maxlength="300"
                    placeholder="请输入项目付款期限"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="投标保证金：" prop="bidBond">
                  <el-input
                    v-model="formParam.bidBond"
                    maxlength="20"
                    placeholder="请输入投标保证金"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="投标保证金期限：" prop="bidBondDeadline">
                  <el-input
                    v-model="formParam.bidBondDeadline"
                    clearable
                    maxlength="300"
                    placeholder="请输入投标保证金期限"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="中标服务费金额：" prop="bidServiceFee">
                  <el-input
                    v-model="formParam.bidServiceFee"
                    clearable
                    maxlength="20"
                    placeholder="请输入中标服务费金额"
                    @change="inputChange('gm')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="投标其他费用：" prop="bidOtherCost">
                  <el-input
                    v-model="formParam.bidOtherCost"
                    maxlength="20"
                    placeholder="请输入投标其他费用"
                    @change="inputChange('gm')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item
                  label="投标项目预计成本总价："
                  prop="totalEstCost"
                >
                  <el-input
                    v-model="formParam.totalEstCost"
                    :disabled="true"
                    placeholder="系统自动计算"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="项目拟投标报价：" prop="tenderOffer">
                  <el-input
                    v-model="formParam.tenderOffer"
                    :disabled="true"
                    placeholder="系统自动计算"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="其中：硬件产品采购价：" prop="hpPrice">
                  <el-input
                    v-model="formParam.hpPrice"
                    clearable
                    maxlength="20"
                    placeholder="请输入硬件产品采购价"
                    @change="inputChange('totalEstCost')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item
                  label="其中：硬件产品拟报价："
                  prop="hardwareOffer"
                >
                  <el-input
                    v-model="formParam.hardwareOffer"
                    clearable
                    maxlength="20"
                    placeholder="请输入硬件产品拟报价"
                    @change="inputChange('tenderOffer')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item
                  label="软件产品成本(含开发)："
                  prop="softwareCost"
                >
                  <el-input
                    v-model="formParam.softwareCost"
                    clearable
                    maxlength="20"
                    placeholder="请输入软件产品成本(含开发)"
                    @change="inputChange('totalEstCost')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="软件产品拟报价：" prop="softwareOffer">
                  <el-input
                    v-model="formParam.softwareOffer"
                    clearable
                    maxlength="20"
                    placeholder="请输入软件产品拟报价"
                    @change="inputChange('tenderOffer')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="实施费用成本：" prop="impCost">
                  <el-input
                    v-model="formParam.impCost"
                    clearable
                    maxlength="20"
                    placeholder="请输入实施费用成本"
                    @change="inputChange('totalEstCost')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="实施费用拟报价：" prop="impOffer">
                  <el-input
                    v-model="formParam.impOffer"
                    clearable
                    maxlength="20"
                    placeholder="请输入实施费用拟报价"
                    @change="inputChange('tenderOffer')"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="质保金的金额：" prop="qgAmount">
                  <el-input
                    v-model="formParam.qgAmount"
                    clearable
                    maxlength="20"
                    placeholder="请输入质保金的金额"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="履约保证金：" prop="pb">
                  <el-input
                    v-model="formParam.pb"
                    clearable
                    maxlength="20"
                    placeholder="请输入履约保证金"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="质保金的期限：" prop="qgDeadline">
                  <el-input
                    v-model="formParam.qgDeadline"
                    clearable
                    maxlength="300"
                    placeholder="请输入质保金的期限"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="履约保证金期限：" prop="pbDeadline">
                  <el-input
                    v-model="formParam.pbDeadline"
                    clearable
                    maxlength="300"
                    placeholder="请输入履约保证金期限"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="投标项目毛利：" prop="gm">
                  <el-input
                    v-model="formParam.gm"
                    :disabled="true"
                    placeholder="系统自动计算"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="gridCol">
                <el-form-item label="毛利率：" prop="gpRate">
                  <el-input
                    v-model="formParam.gpRate"
                    :disabled="true"
                    placeholder="系统自动计算"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 投标项目评分情况 -->
          <el-collapse-item v-if="formParam.proType == 1" disabled name="4">
            <template #title>
              <title-name
                class="title text-#000000 ml-20px"
                icon="i-carbon-bookmark-filled"
                title="投标项目评分情况"
              />
            </template>
            <el-row :gutter="grid" class="px-20">
              <Scoring
                ref="scoringChind"
                :scaleMarkVos="scaleMarkVos ? scaleMarkVos : []"
              ></Scoring>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>
    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="
        formParam.proSchedule != '3' ? flowOptions : projectClosingFlow
      "
      @close="handleClose('examine')"
      @initiate="handleClose('initiate')"
    ></SubmissionProcess>
    <!-- 弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @close="dialogParam.isDialog = false"
      @ok="selectDialogData"
    ></SelectDialog>
    <!-- 关联项目 -->
    <RelatedProject
      :relatedParams="params"
      @closeDialog="closeDialog"
      @relatedOver="relatedOver"
    />
    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
      @ok="selectCustomerData"
    ></SelectCustomer>
  </div>
</template>
<script name="AddProject" setup>
import { ElLoading } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import Scoring from './module/scoring.vue'
import { formRules } from '../module/formData'
import {
  project_phase, //项目阶段
  project_properties, //项目属性
  business_attribute, //业务属性
  project_amount, //项目金额
  bidding_form, //招标形式
  reminder_opening, //开标提醒(提醒时间)
  reminder_method, //提醒方式
  parentOptions,
  queryCustomer,
  bidding_unit,
  loadingSelect, //远程检索loading
  projectOptions //项目数据
} from '@/hooks/dict/useProject'
import { companyOption } from '@/hooks/dict/order'
import { getNodeData } from '@/api/workflow/process'
import { getDetailTactlistByCactName } from '@/api/customerManage/customerList'
import useCommonStore from '@/store/modules/common'
import { getPricipalId } from '@/utils/commo'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import useTagsViewStore from '@/store/modules/tagsView'
import * as Api from '@/api/projectManage/project'
import { skipToError } from '@/utils/commo'
import { getLatestMsg, addManage } from '@/api/system/notice'
import { createContact } from '@/api/customerManage/contactList'
import { pushNotifications } from '@/hooks/notification/push'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import { format } from 'date-fns'
import { listProcess, getBusinessProStatus } from '@/api/workflow/process'
import { isNumber } from '@/utils/validate'

const route = useRoute()
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
// 用户数据
const userStore = useUserStore()
const projectId = ref(null)
const fileBtnType = ref(1) //默认值为1，这是区分投标附件上传还是附件上传
//表单内的栅格化设置
const grid = ref(20)
const gridCol = ref(12)
const isEdit = ref(true) //是否是流程详情。但是流程中不能编辑
const data = reactive({
  proMsgData: {}, // 消息推送参数
  scaleMarkVos: [], //投标项目评分情况  查询的时候
  dialogParam: {},
  activeNames: ['1', '2', '3', '4'],
  selectOptionObj: {}, // select
  formParam: {
    cusType: 'customer', //客户名称 类型 企业客户 customer 个人客户 cusLink
    proName: null, //项目名称
    proType: '2', //项目属性
    proNum: null, //项目编号
    cusId: null, //客户名称 id
    cusLinkId: null, //客户联系人id
    proSchedule: '1', // 项目阶段
    busType: null, //业务属性
    companyId: null, //
    deptId: null, //归属单位
    cusName: null, //客户联系人
    principalId: null, //项目负责人
    phone: null, //联系电话
    proSum: 0, //项目金额
    linkProjectId: null, //关联项目
    proRemark: null, //
    materials: null, //项目所需材料
    tenderer: null, //投标单位
    tenderType: null,
    projectScale: null, //项目规模
    bidOpeningTime: null, //开标时间
    bidOpeningReminder: null, //开标提醒
    reminderType: ['0'], //提醒方式
    sysAttachFiles: null, //文件
    /**投标项目财务情况 */
    proSumResouce: null, // 项目资金来源
    proPaymentDeadline: null, //项目付款期限
    bidBond: null, //投标保证金
    bidBondDeadline: null, //投标保证金期限
    bidServiceFee: null, //中标服务费金额
    bidOtherCost: null, //投标其他费用
    totalEstCost: null, //投标项目预计成本总价
    tenderOffer: null, //项目拟投标报价
    hpPrice: null, //其中：硬件产品采购价
    hardwareOffer: null, //其中：硬件产品拟报价
    softwareCost: null, //软件产品成本（含开发）
    softwareOffer: null, //软件产品拟报价
    impCost: null, //实施费用成本
    impOffer: null, //实施费用拟报价
    qgAmount: null, //质保金的金额
    pb: null, //履约保证金
    qgDeadline: null, //质保金的期限
    pbDeadline: null, //履约保证金期限
    gm: null, //投标项目毛利
    gpRate: null //毛利率
  }
})
const {
  scaleMarkVos,
  dialogParam,
  selectOptionObj,
  activeNames,
  formParam,
  proMsgData
} = toRefs(data)
const examineParam = ref({})
const openLoading = ref(null) // 加载状态
const props = defineProps({
  id: {
    type: String || Number
  }
})
const openLoadingFn = () => {
  openLoading.value = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
// 监听项目属性是否编辑
const isProType = computed(() => {
  if (location.href.match(/addProject/)) {
    return false
  } else {
    return true
  }
})

/**
 * 查询项目
 */
async function getProInfoFn() {
  openLoadingFn()
  try {
    const response = await Api.getProInfo({ projectId: projectId.value })
    proxy.$refs['ruleFormRef'].resetFields()
    let data = {
      ...response.data.pro
    }

    if (response.data.finance) {
      data = Object.assign({}, data, response.data.finance)
    }
    if (response.data.bidding) {
      data = Object.assign({}, data, response.data.bidding)
    }
    //投标项目评分情况
    scaleMarkVos.value = response.data.scaleMarkVos
    // 获取客户名称
    parentOptions.value = [
      {
        id: data.cusId,
        customerName: data.customer
      }
    ]
    //获取客户联系人
    contactsOptions.value = [
      { contactName: data.cusLinkName, id: data.cusLinkId }
    ]
    formParam.value = data
    // 项目阶段为执行阶段时 ，项目完结是否发起申请--项目完结发起申请
    if (formParam.value.proSchedule == '3') {
      let statusRes2 = await getBusinessProStatus({
        businessId: formParam.value.ConclusionId
      })
      if (statusRes2.data.canStart) {
        // canStart false时 不能发起，true则可以发起
        initFlowFn('30')
        projectClosing_isCanStart.value = true
      } else {
        projectClosing_isCanStart.value = false
      }
    }

    // 获取文件
    fileList_zb.value = response.data.bidding
      ? response.data.bidding.sysAttachFiles
      : []
    fileList_ht.value = response.data?.pro?.sysAttachFiles
    let flowRes = await getNodeData(projectId.value) //获取当前流程节点
    bpmnStatus.value = flowRes.data?.nowTaskName
    isEdit.value =
      flowRes.data == null || flowRes.data?.isFirst == 'Y' ? true : false
    // 获取项目负责人
    await getDefaultUserInfo(formParam.value.principalId)
    //关联项目数据
    // if (response.data.pro && response.data.pro.linkProjectId) {
    //   projectOptions.value = [
    //     {
    //       proName: response.data?.pro?.linkProjectName,
    //       projectId: response.data?.pro?.linkProjectId
    //     }
    //   ]
    // }
    //归属单位
    formParam.value.companyId =
      response.data.pro && response.data.pro.companyId
        ? Number(response.data.pro.companyId)
        : null
    let lables = filterFn(
      companyOption.value,
      formParam.value.companyId,
      'companyId'
    )
    if (!lables) {
      companyOption.value.push({
        id: formParam.value.companyId,
        label:
          response.data.pro && response.data.pro.companyName
            ? response.data.pro.companyName
            : null
      })
    }
    console.log(lables, '归属单位')

    // 消息提醒
    const resp = await getLatestMsg({
      businessId: '项目-开标-' + projectId.value
    })
    if (resp.code === 200 && resp.data) {
      formParam.value.bidOpeningReminder = resp.data.followType
      formParam.value.reminderType = resp.data.reminderMethod.split(',')
    }
    openLoading.value.close()
  } catch (error) {
    openLoading.value.close()
  }
  // 流程中的时候 是不能发起项目完结申请
  if (location.href.match(/detail/) || location.href.match(/workDetail/)) {
    projectClosing_isCanStart.value = false
  }
}

// 过滤数据 获取中文
const filterFn = (data, id, type) => {
  let newData = JSON.parse(JSON.stringify(data))
  let reData = []
  if (!newData) {
    return false
  }
  if (type == 'companyId') {
    reData = getTreeNodeByParam(
      companyOption.value,
      formParam.value.companyId,
      'id',
      []
    )
    return reData && reData.length > 0 ? reData[0].label : ''
  } else {
    reData = newData.filter(item => {
      return item.id == id
    })
    return reData && reData.length > 0 ? reData[0][type] : ''
  }
}

/***客户名称弹出框  start */
const dialogParamA = ref({
  type: 'customer'
})
/**5、获取选中的值
 *
 *@param val
 type 业务类型
 selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 labelData 选中的数据label ['王晓易']
 defaultCheckedKeys 选中的数据id [1]
 dialogVisible: false 弹出框的关闭
 */
// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customer':
      formParam.value.cusType = val.tabVal
      formParam.value.customer = val.labelData.toString()
      if (formParam.value.cusId !== val.defaultCheckedKeys.toString()) {
        formParam.value.linkProjectId = ''
        formParam.value.linkProjectName = ''
        if (val.tabVal == 'customer') {
          //企业客户
          changeCustomer(val.defaultCheckedKeys.toString(), 'customer')
        }
      }
      if (val.tabVal == 'cusLink') {
        // 个人客户
        formParam.value.cusLinkId = val.defaultCheckedKeys.toString()
        formParam.value.cusLinkName = val.labelData.toString()
        formParam.value.phone = val.selectData
          ? val.selectData[0].contactNumber
          : ''
      }
      formParam.value.cusId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
  }
}
/***客户名称弹出框  end */
/****    关联项目  start   ***/

const params = ref({
  visible: false,
  businessId: formParam.value.cusId,
  businessName: formParam.value.customer
})

// 打开弹窗
function activeDialog(type) {
  if (type == 'linkProject') {
    const id = formParam.value.cusId
    if (!id) {
      proxy.$modal.msgError('请先选择客户名称')
      return false
    }
    const ids = formParam.value.linkProjectId
    params.value = {
      visible: true, // 显示dialog
      businessId: id, // 根据id查询合同列表
      businessName: formParam.value.customer,
      multiple: false, // 是否多选
      defaultSelect: ids ? ids : [] // 默认选择数据
    }
  } else {
    //客户名称选择
    dialogParamA.value.tabVal = formParam.value.cusType || 'customer'
    dialogParamA.value.title = '选择客户名称'
    dialogParamA.value.isDialog = true
    dialogParamA.value.multiple = false
    dialogParamA.value.nodeKey = 'id'
    dialogParamA.value.defaultCheckedKeys = [formParam.value.cusId]
    dialogParamA.value.defaultCheckedLabel = formParam.value.customer
  }
}

// 弹窗确认完成回调
function relatedOver(val) {
  if (val) {
    const name = params.value.multiple
      ? val.map(v => v.proName).toString() || ''
      : val.proName

    const ids = params.value.multiple
      ? val.map(v => v.projectId) || []
      : val.projectId

    formParam.value.linkProjectId = ids
    formParam.value.linkProjectName = params.value.multiple
      ? val.map(v => v.proName)
      : name
  }

  closeDialog()
}

// 关闭弹窗
function closeDialog() {
  params.value.visible = false
}

// el-input clear函数
function clearAll(type) {
  if (type == 'linkProject') {
    // 关联项目
    formParam.value.linkProjectId = ''
    formParam.value.linkProjectName = ''
  } else {
    //客户名称
    formParam.value.cusId = ''
    formParam.value.customer = ''
    formParam.value.cusLinkId = ''
    formParam.value.cusLinkName = ''
    formParam.value.phone = ''
    formParam.value.linkProjectId = ''
    formParam.value.linkProjectName = ''
  }
}

/****    关联项目  end   ***/
/***客户联系人数据  start*/
const contactsOptions = ref([])
// 改变客户名称后客户联系人 联系电话清空
const changeCustomer = async (val, type) => {
  // //获取客户联系人
  await queryContacts(val, type)
  if (!val) {
    formParam.value.cusLinkId = ''
    formParam.value.cusLinkName = ''
    formParam.value.phone = ''
    return false
  }
  formParam.value.cusLinkId =
    contactsOptions.value && contactsOptions.value.length > 0
      ? contactsOptions.value[0].id
      : ''
  formParam.value.cusLinkName =
    contactsOptions.value && contactsOptions.value.length > 0
      ? contactsOptions.value[0].contactName
      : ''
  formParam.value.phone =
    contactsOptions.value && contactsOptions.value.length > 0
      ? contactsOptions.value[0].contactNumber
      : ''
}
const cuslinkLoading = ref(false)

/**
 * 客户联系人模糊搜索
 * @param val 当前输入的值
 */
async function queryContacts(val, type) {
  if (!type && !formParam.value.cusId) {
    proxy.$modal.msgError('客户名称不能为空')
    return
  }
  loadingSelect.value = true
  let params = {
    pageSize: 10,
    entId: type && formParam.value.cusId != val ? val : formParam.value.cusId,
    contactName: type ? '' : val || ''
  }
  let res = await getDetailTactlistByCactName(params)
  contactsOptions.value = res.data
  loadingSelect.value = false
}

// 客户联系人选中事件
const contactsChange = val => {
  if (!val) {
    formParam.value.cusLinkName = ''
    return false
  }
  const cusId_val = Number(val)
  if (isNaN(cusId_val)) {
    // 新增联系人
    formParam.value.cusLinkName = val
    formParam.value.phone = ''
    return false
  }
  let newData = JSON.parse(JSON.stringify(contactsOptions.value))
  if (newData.length == 0) {
    return false
  }
  let obj = newData.filter(item => {
    return item.id == val
  })
  formParam.value.cusLinkName = obj[0].contactName
  formParam.value.phone = obj[0].contactNumber
}
/***客户联系人数据  end*/
const scoringChind = ref(null) //scoring 的组件
// 获取表单字段
const getFormParam = saveType => {
  let param = {}
  let principalId = null
  if (formParam.value.principalId) {
    principalId = getPricipalId(
      selectOptionObj.value['principalId'],
      formParam.value.principalId
    )
  }

  //基本参数
  let baseParams = {
    busType: formParam.value.busType,
    businessBelong: formParam.value.businessBelong,
    companyId: formParam.value.companyId, //归属单位
    companyName: filterFn(
      companyOption.value,
      formParam.value.companyId,
      'companyId'
    ),
    cusId: formParam.value.cusId || null, //客户名称 id
    customer: formParam.value.customer,
    cusLinkId: formParam.value.cusLinkId, //客户联系人id
    cusLinkName: formParam.value.cusLinkName, //客户联系人 名称
    cusType: formParam.value.cusType, //客户类型 企业客户 customer 个人客户 cusLink
    phone: formParam.value.phone, //联系电话
    // 获取项目id
    principalId: principalId ? principalId.toString() : null, //项目负责人id
    principal: formParam.value.principal, //项目负责人
    proName: formParam.value.proName, //项目名称
    proNum: formParam.value.proNum, //
    proSum: formParam.value.proSum || 0, //项目金额
    proRemark: formParam.value.proRemark,
    proSchedule: formParam.value.proSchedule,
    proType: formParam.value.proType,
    materials: formParam.value.materials,
    linkProjectId: formParam.value.linkProjectId, //关联项目
    linkProjectName: formParam.value.linkProjectName, //关联项目名称
    projectId: null, //项目信息id
    status: 0, //0正常1有风险2失控
    sysAttachFiles: fileList_ht.value || []
  }

  if (formParam.value.proType == '1') {
    if (saveType == 'save') {
      // 投标项目
      const resp = bidOpeningMsg()
      if (!resp) {
        // 开标消息未填完整
        return
      }
      // if (
      //   JSON.stringify(fileList_zb.value) == '[]' &&
      //   typeof fileList_zb.value == 'object'
      // ) {
      //   proxy.$modal.msgError('招标文件必填')
      //   return false
      // }
      // 投标报价不能大于项目规模
      if (
        parseFloat(formParam.value.tenderOffer) >
        parseFloat(formParam.value.projectScale)
      ) {
        proxy.$modal.msgError('投标报价不能大于项目规模')
        return false
      }
    }

    //投标
    param = {
      bidding: {
        tenderer: formParam.value.tenderer, //投标单位
        tenderType: formParam.value.tenderType,
        projectScale: formParam.value.projectScale,
        bidOpeningTime: formParam.value.bidOpeningTime
          ? formParam.value.bidOpeningTime.length > 10
            ? formParam.value.bidOpeningTime
            : formParam.value.bidOpeningTime + ' 00:00:00'
          : null,
        sysAttachFiles: fileList_zb.value || []
      },
      finance: {
        proSumResouce: formParam.value.proSumResouce, // 项目资金来源
        proPaymentDeadline: formParam.value.proPaymentDeadline, //项目付款期限
        bidBond: formParam.value.bidBond, //投标保证金
        bidBondDeadline: formParam.value.bidBondDeadline, //投标保证金期限
        bidServiceFee: formParam.value.bidServiceFee, //中标服务费金额
        bidOtherCost: formParam.value.bidOtherCost, //投标其他费用
        totalEstCost: formParam.value.totalEstCost, //投标项目预计成本总价
        tenderOffer: formParam.value.tenderOffer, //项目拟投标报价
        hpPrice: formParam.value.hpPrice, //其中：硬件产品采购价
        hardwareOffer: formParam.value.hardwareOffer, //其中：硬件产品拟报价
        softwareCost: formParam.value.softwareCost, //软件产品成本（含开发）
        softwareOffer: formParam.value.softwareOffer, //软件产品拟报价
        impCost: formParam.value.impCost, //实施费用成本
        impOffer: formParam.value.impOffer, //实施费用拟报价
        qgAmount: formParam.value.qgAmount, //质保金的金额
        pb: formParam.value.pb, //履约保证金
        qgDeadline: formParam.value.qgDeadline, //质保金的期限
        pbDeadline: formParam.value.pbDeadline, //履约保证金期限
        gm: formParam.value.gm, //投标项目毛利
        gpRate: formParam.value.gpRate //毛利率
      },
      pro: baseParams,
      score: scoringChind.value.tableData || []
    }
  } else {
    // 直接合同
    param = {
      bidding: formParam.value.tenderer
        ? { tenderer: formParam.value.tenderer, bid: formParam.value.bid }
        : null,
      finance: null,
      pro: baseParams,
      score: null
    }
  }
  if (projectId.value) {
    // 修改
    param.pro.projectId = projectId.value
    if (formParam.value.proType == '1') {
      param.bidding.bid = formParam.value.bid
      param.finance.fid = formParam.value.fid
    }
  }
  return param
}
/**流程 同意时调的保存 方法 */
const handleSave = async () => {
  return await handleSaveFn('flow')
}
/** 项目列表的时候保存时 暂存的意思，在流程中 就是保存 需要验证数据*/
const stagingFn = async () => {
  if (!formParam.value.proName) {
    proxy.$modal.msgWarning('项目名称不能为空')
    return false
  }
  if (!formParam.value.cusId) {
    proxy.$modal.msgWarning('客户名称不能为空')
    return false
  }
  let param = getFormParam('staging')
  if (projectId.value) {
    await Api.updateOrdproject(param)
    if (location.href.match(/addProject/)) {
      await getProInfoFn() //查询详情
    }
    // 保存接口才有
    proxy.useReturn(
      '',
      () => {
        handleBack()
      },
      async () => {}
    )
  } else {
    // 新增
    Api.addOrdproject(param).then(async res => {
      examineParam.value.businessId = res.data
      projectId.value = res.data
      await getProInfoFn() //查询详情
      // 保存接口才有
      proxy.useReturn(
        '',
        () => {
          handleBack()
        },
        async () => {}
      )
    })
  }
}
/** 该业务需要调的 保存接口 */
/**type 那种类型
 * flowStatus  发起流程申请的业务不一样
 * */
const handleSaveFn = async type => {
  return new Promise((resolve, reject) => {
    console.log(isEdit.value, 'isEdit--')
    if (!isEdit.value) {
      // 如果不是第一环节不能调保存接口
      console.log('不是第一环节')
      resolve()
      return false
    }
    proxy.$refs['ruleFormRef'].validate(async valid => {
      if (!valid) {
        reject(new Error('Validation failed'))
        skipToError()
        return false
      }
      let param = getFormParam('save')
      if (!param) {
        reject(new Error('Validation failed'))
        return false
      }
      const cusId_val = Number(formParam.value.cusLinkId)
      if (isNaN(cusId_val)) {
        //如果id 是文字就是新增
        let contactParams = {
          co: {
            contactName: formParam.value.cusLinkName, //联系人名称
            contactNumber: formParam.value.phone, //联系人电话
            contactType: '1',
            deptId: userStore.user.deptId, //登录人部门
            entId: formParam.value.cusId, //客户id
            entType: '1',
            orgId: userStore.user.orgId, //登录人公司
            origin: '9',
            userId: userStore.user.userId, //登录人id
            userName: userStore.user.nickName, //登录账号 都是当前登录人的
            starRating: 0
          },
          eo: {
            cultivateIndus: '1',
            isTwentyfive: 'y'
          }
        }
        try {
          // 需要新增客户
          let contantRes = await createContact(contactParams)
          if (contantRes.code != 200) {
            reject(new Error('接口错误'))
            return false
          }
          formParam.value.cusLinkId = contantRes.data
          contactsOptions.value = [
            { contactName: formParam.value.cusLinkName, id: contantRes.data }
          ]
          resolve()
        } catch (e) {
          // 发生错误，reject
          reject(e)
          return false
        }
      }
      param.pro.cusLinkId = formParam.value.cusLinkId
      if (projectId.value) {
        try {
          await Api.updateOrdproject(param)
          await notification(projectId.value)
          if (location.href.match(/addProject/)) {
            await getProInfoFn() //查询详情
          }
          if (type == 'examine') {
            // 点击提交审批
            handleExamine()
          } else if (type != 'flow') {
            let hrefs = location.href.match(/workDetail/)
            if (!hrefs) {
              // 保存接口才有
              proxy.useReturn(
                '',
                () => {
                  handleBack()
                },
                async () => {}
              )
            } else {
              proxy.$modal.msgSuccess('保存成功')
            }
          }
          resolve()
        } catch (e) {
          // 发生错误，reject
          reject(e)
        }
      } else {
        // 新增
        Api.addOrdproject(param).then(async res => {
          notification(res.data)
          examineParam.value.businessId = res.data
          projectId.value = res.data
          await getProInfoFn() //查询详情
          if (type == 'examine') {
            // 点击发起申请
            await handleExamine()
          } else {
            // 保存接口才有
            proxy.useReturn(
              '',
              () => {
                handleBack()
              },
              async () => {}
            )
          }
        })
      }
    })
  })
}

/*** 文件上传 start */
let fileList_zb = ref([])
let fileList_ht = ref([])

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      console.log(fileBtnType.value, 'fileBtnType.value--')
      if (fileBtnType.value == '1') {
        //招标
        fileList_zb.value.push(res.data)
      } else {
        fileList_ht.value.push(res.data)
      }
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}

// 删除文件
async function delFileName(index, type) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      //招标
      const file =
        type == '1' ? fileList_zb.value[index] : fileList_ht.value[index]

      const res = await delFile(file.fileName)
      if (res.code === 200) {
        if (type == '1') {
          //招标
          fileList_zb.value.splice(index, 1)
        } else {
          fileList_ht.value.splice(index, 1)
        }
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

/*****文件上传 end */
const isValFn = a => {
  if (JSON.stringify(a) == '{}') {
    return false
  }
  return Object.entries(a).every(
    ([key, value]) => value !== null && value !== '' && !isNaN(value)
  )
}
/**
 *表单验证计算
 投标项目预计成本总价=其中：硬件产品采购价+软件产品成本（含开发）+实施费用成本
 项目拟投标报价=其中：硬件产品拟报价+软件产品拟报价+实施费用拟报价
 投标项目毛利（万元）=项目拟投标报价-投标项目预计成本总价-中标服务费金额-投标其他费用（如标书等）
 毛利率=投标项目毛利/项目拟投标报价
 * @param {*} type
 */
const inputChange = type => {
  switch (type) {
    case 'totalEstCost':
      // 投标项目预计成本总价=其中：硬件产品采购价+软件产品成本（含开发）+实施费用成本
      let vals = isValFn({
        hpPrice: formParam.value.hpPrice,
        softwareCost: formParam.value.softwareCost,
        impCost: formParam.value.impCost
      })
      if (vals) {
        formParam.value.totalEstCost =
          ((
            parseFloat(formParam.value.hpPrice) +
            parseFloat(formParam.value.softwareCost) +
            parseFloat(formParam.value.impCost)
          ).toFixed(8) *
            100000000) /
          100000000
      } else {
        formParam.value.totalEstCost = null
      }
      break
    case 'tenderOffer':
      //项目拟投标报价=其中：硬件产品拟报价+软件产品拟报价+实施费用拟报价
      let vals2 = isValFn({
        hardwareOffer: formParam.value.hardwareOffer,
        softwareOffer: formParam.value.softwareOffer,
        impOffer: formParam.value.impOffer
      })
      console.log(
        vals2,
        {
          hardwareOffer: formParam.value.hardwareOffer,
          softwareOffer: formParam.value.softwareOffer,
          impOffer: formParam.value.impOffer
        },
        'vals2'
      )
      if (vals2) {
        formParam.value.tenderOffer =
          ((
            parseFloat(formParam.value.hardwareOffer) +
            parseFloat(formParam.value.softwareOffer) +
            parseFloat(formParam.value.impOffer)
          ).toFixed(8) *
            100000000) /
          100000000
      } else {
        formParam.value.tenderOffer = null
      }

      break
  }
  //投标项目毛利（万元）=项目拟投标报价-投标项目预计成本总价-中标服务费金额-投标其他费用（如标书等）
  let mlType = isValFn({
    tenderOffer: formParam.value.tenderOffer,
    bidServiceFee: formParam.value.bidServiceFee,
    totalEstCost: formParam.value.totalEstCost,
    bidOtherCost: formParam.value.bidOtherCost
  })
  console.log(
    mlType,
    {
      tenderOffer: formParam.value.tenderOffer,
      bidServiceFee: formParam.value.bidServiceFee,
      totalEstCost: formParam.value.totalEstCost,
      bidOtherCost: formParam.value.bidOtherCost
    },
    'mlType-'
  )
  if (mlType) {
    formParam.value.gm =
      ((
        parseFloat(formParam.value.tenderOffer) -
        parseFloat(formParam.value.totalEstCost) -
        parseFloat(formParam.value.bidServiceFee) -
        parseFloat(formParam.value.bidOtherCost)
      ).toFixed(8) *
        100000000) /
      100000000
  } else {
    formParam.value.gm = null
  }
  // 毛利率=投标项目毛利/项目拟投标报价
  let mlType2 = isValFn({
    gm: formParam.value.gm,
    tenderOffer: formParam.value.tenderOffer
  })
  console.log(mlType2, formParam.value.tenderOffer, 'mlType2')
  if (mlType2 && formParam.value.tenderOffer != 0) {
    //百分比%+俩位小数点：67.78%
    formParam.value.gpRate =
      (
        (parseFloat(formParam.value.gm) /
          parseFloat(formParam.value.tenderOffer)) *
        100
      ).toFixed(2) + '%'
  } else {
    formParam.value.gpRate = null
  }
}

/**** 项目负责人 模块 start */
/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId) {
  if (!userId) {
    return false
  }
  let id = userId
  //获取人员数据
  const deptUserData = await commonStore.getUseTreeData()
  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
  if (obj && obj.length > 0) {
    selectOptionObj.value.principalId = obj
    formParam.value.principalId = obj && obj.length > 0 ? obj[0].uuid : ''
  } else {
    selectOptionObj.value.principalId = [
      { label: formParam.value.principal, uuid: formParam.value.principalId }
    ]
  }
}

/**
 * 项目负责人获取焦点事件
 */
function userInputFocus() {
  dialogParam.value = {
    type: 'principalId',
    title: '请选择项目负责人',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: false,
    checkStrictly: false
  }
  dialogParam.value.isDialog = true
  dialogParam.value.defaultCheckedKeys = [formParam.value.principalId] || []
  console.log(dialogParam.value, '  dialogParam.value-')
}

/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'principalId':
      selectOptionObj.value['principalId'] = val.selectData
      formParam.value.principal = val.labelData.toString()
      formParam.value.principalId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : ''
      break
  }
}
/**** 项目负责人 模块 end */
const router = useRouter()
// 返回
const handleBack = () => {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}

/**消息推送 */
function bidOpeningMsg() {
  if (formParam.value.proType === '1') {
    let principalId = getPricipalId(
      selectOptionObj.value['principalId'],
      formParam.value.principalId
    )
    const obj = {}
    let resp = true
    const num = [0, 1, 3, 5, 7][Number(formParam.value.bidOpeningReminder)]
    const time =
      formParam.value.bidOpeningTime && (num || num === 0)
        ? format(
            new Date(
              new Date(formParam.value.bidOpeningTime).getTime() -
                num * 24 * 60 * 60 * 1000
            ),
            'yyyy-MM-dd 00:00:00'
          )
        : ''
    obj.receiver = (formParam.value.principalId || '')
      .toString()
      .replace(/U/gi, '')
    obj.content = `${formParam.value.proName}开标时间：${formParam.value.bidOpeningTime},请知悉`
    obj.sendTime = time
    obj.reminderMethod =
      !formParam.value.reminderType ||
      (formParam.value.reminderType &&
        formParam.value.reminderType.length === 0)
        ? ''
        : formParam.value.reminderType.toString()
    obj.impSign = '2'
    obj.serviceType = '0'
    obj.urgFlag = '1'
    obj.receiverName = formParam.value.principal
    obj.followType = formParam.value.bidOpeningReminder
      ? formParam.value.bidOpeningReminder
      : null
    // obj.followDate = formParam.value.bidOpeningTime
    obj.urlName = '前往详情'
    obj.title = `${formParam.value.proName}的开标提醒`
    obj.type = '0'
    obj.sender = userStore.user.nickName
    // if (!formParam.value.bidOpeningReminder && obj.reminderMethod) {
    //   proxy.$modal.msgWarning('请选择开标提醒')
    //   return false
    // }
    if (formParam.value.bidOpeningReminder && !obj.reminderMethod) {
      proxy.$modal.msgWarning('请选择提醒方式')
      return false
    }
    if (!formParam.value.bidOpeningReminder && !obj.reminderMethod) {
      obj.receiver = ''
      obj.receiverName = ''
    }
    // const result = pushNotifications(obj, ['followType', 'reminderType'])
    // if (!result) {
    //   proxy.$modal.msgWarning('开标消息提醒存在未填内容，请先填写完整')
    //   resp = false
    // } else {
    proMsgData.value = obj
    return true
    // }
  }
}

function notification(id) {
  console.log(formParam.value.bidOpeningReminder, formParam.value.reminderType)
  if (
    (formParam.value.bidOpeningReminder &&
      formParam.value.reminderType &&
      formParam.value.reminderType.length) ||
    (!formParam.value.bidOpeningReminder &&
      (!formParam.value.reminderType || !formParam.value.reminderType.length))
  ) {
    const url = `/sales/projectManage/projectDetails?id=${id}`
    proMsgData.value.url = url
    proMsgData.value.businessId = '项目-开标-' + id
    addManage(proMsgData.value)
  }
}

/***************************业务流程 模块 start****************************************************************/
const isExamine = ref(true) //流程是判断是否走审批按钮
const flowOptions = ref([]) //该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情
/*****审批模块  start*** */
/**
 * 提交流程审批
 * type  发起申请业务不一样
 */
const handleExamine = type => {
  examineParam.value.businessId =
    type == 'projectClosing'
      ? formParam.value.ConclusionId
      : examineParam.value.businessId
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = formParam.value.proName //项目名称
  examineParam.value.amount = formParam.value.proSum //项目金额
  examineParam.value.categoryCode = type == 'projectClosing' ? '30' : '0' //分类编码：项目1，订单2 客户3 	投标4 项目结项申请30
  examineParam.value.visible = true
  console.log(examineParam.value, 'examineParam.value')
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      //如果流程只有一个 则提示去编辑页面发起并关闭当前流程
      // if (
      //   flowOptions.value.length == 1 &&
      //   !!location.href.match(/addProject/)
      // ) {
      //   // proxy.$modal.msg('取消后，请去编辑项目进行发起')
      //   handleBack()
      // }
      break
    case 'initiate':
      //审批 发起成功
      examineParam.value.visible = false
      handleBack()
      break
  }
}
/*****审批模块  end*** */
/** 项目结项申请模块-star*/
const projectClosingFlow = ref([]) //项目结项流程
//发起
const projectClose = async () => {
  //项目完结申请
  await initFlowFn('30')
  // 2.根据
  if (JSON.stringify(projectClosingFlow.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    proxy.$modal.msgError('该业务没有配置项目结项流程，请先创建流程')
  } else {
    // 发起流程
    handleExamine('projectClosing')
  }
}
/** 项目结项申请模块-end*/
/**
 *
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * * 2.2只有一条流程时，则不弹出框流程提交审核按钮隐藏，直接保存(得到返回的业务id) 现实下一环节人的显示及弹出框 -再发起
 * * 2.3多条流程时，点击保存(得到返回的业务id) ，再点击提交审核按钮，弹出框现实流程，直接保存(得到返回的业务id) 现实下一环节人的显示及弹出框 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3
 */
const initFlowFn = async type => {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  if (type == '30') {
    projectClosingFlow.value = comRes.rows || []
  } else {
    flowOptions.value = comRes.rows || []
    // 2.根据
    if (JSON.stringify(flowOptions.value) == '[]') {
      //2.1 没有流程-提示不能新建数据
      if (location.href.match(/addProject/)) {
        // 新建页面
        proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
        handleBack()
      } else {
        //编辑页面
        isExamine.value = false
      }
    } else {
      isExamine.value = true
      //   else if (flowOptions.value.length == 1) {
      //   //2.2 流程只有一个，只有一条流程时，则不弹出框流程提交审核按钮隐藏，直接点击保存
      //   // isExamine.value = false
      // } else {
      //   //2.3多条流程时
      // }
    }
  }
}
// 编辑页面的时候 -》根据业务查询审批状态(其实就看这个流程有没有发起过)
const projectClosing_isCanStart = ref(true) //判断该项目阶段为执行阶段时 ，项目完结是否发起申请 ===》针对编辑页面
const getBusinessProStatusFn = async () => {
  // 项目是否发起申请
  let statusRes = await getBusinessProStatus({ businessId: projectId.value })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    initFlowFn('0')
    isCanStart.value = true
  } else {
    isCanStart.value = false
  }
}
/*
 **************************业务流程 模块 end****************************************************************/
// 将 handleSave 暴露 流程环节中使用
defineExpose({
  handleSave
})
const bpmnStatus = ref('')
const isFlow = ref(false)
watch(
  () => props.id,
  val => {
    if (val && !!location.href.match(/editProject/)) {
      isFlow.value = false
      projectId.value = val
      examineParam.value.businessId = val
      getProInfoFn() //查询详情接口
      //根据业务查询审批状态
      getBusinessProStatusFn()
    } else if (
      (val && !!location.href.match(/detail/)) ||
      (val && !!location.href.match(/workDetail/))
    ) {
      isCanStart.value = false
      isFlow.value = true
      // 待办详情-访问
      projectId.value = val
      getProInfoFn() //查询详情接口
    } else if (location.href.match(/addProject/)) {
      isFlow.value = false
      isExamine.value = true
      isEdit.value = true
      // 走业务流程
      initFlowFn('0')
    }
  },
  {
    immediate: true
  }
)
watch(
  () => route.query,
  val => {
    if (route.query && route.query.id && !!location.href.match(/addProject/)) {
      //关联项目数据
      projectOptions.value = [
        {
          proName: route.query?.name,
          projectId: route.query.id
        }
      ]
      formParam.value.linkProjectId = route.query.id
    }
    if (location.href.match(/addProject/)) {
      //归属单位 默认值当前用户所在单位
      formParam.value.companyId = userStore.user.orgId
    }
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss">
.projectM_sty .el-collapse {
  border-top: none !important;
  border-bottom: none !important;
}

:deep(.el-radio.is-bordered) {
  border-radius: 30px;
}
</style>
